package com.rpp.dao.impl;

import com.rpp.annotation.Autowired;
import com.rpp.annotation.Repository;
import com.rpp.dao.AccountDao;
import com.rpp.pojo.Account;
import com.rpp.utils.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Description
 * @Author rpp
 * @Date 2020/6/25 9:54 下午
 */
@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    /**
     * 根据卡号查询账户信息
     *
     * @param cardNo
     * @return
     * @throws Exception
     */
    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {

        Connection connection = connectionUtils.getCurrentThreadConn();

        String sql = "select * from tbl_account where cardNo = " + cardNo;
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        Account account = new Account();
        while (resultSet.next()) {
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
            account.setCardNo(resultSet.getString("cardNo"));
        }
        //关闭连接
        resultSet.close();
        preparedStatement.close();
        return account;
    }

    /**
     * 更新账户信息
     *
     * @param account
     * @return
     * @throws Exception
     */
    @Override
    public int updateAccountByCardNo(Account account) throws Exception {

        Connection connection = connectionUtils.getCurrentThreadConn();

        String sql = "update tbl_account set money = ? where cardNo = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //设置参数
        preparedStatement.setInt(1, account.getMoney());
        preparedStatement.setString(2, account.getCardNo());
        //更新数据
        int res = preparedStatement.executeUpdate();

        preparedStatement.close();

        return res;
    }
}
